//
//  JCFriendViewController.m
//  ERP
//
//  Created by goldeney on 15/7/13.
//  Copyright (c) 2015年 ShangHai Goldeneye Techonology Co.,Ltd. All rights reserved.
//

#import "JCFriendViewController.h"
#import "UIColorDispose.h"
#import "UITableView+Custom.h"

#import "JCFriendViewCell.h"
#import "OAAddressBookCatalogViewController.h"

//#import "XMPPConnectService.h"
//#import "JBChatFriendViewController.h"
//
//#import "DDLog.h"
//
//// Log levels: off, error, warn, info, verbose
//#if DEBUG
//static const int ddLogLevel = LOG_LEVEL_VERBOSE;
//#else
//static const int ddLogLevel = LOG_LEVEL_INFO;
//#endif

@interface JCFriendViewController ()<UISearchBarDelegate,NSFetchedResultsControllerDelegate>
{
    NSFetchedResultsController *fetchedResultsController;
}

@property (strong, nonatomic) NSArray *functionArray;
@property (strong, nonatomic) NSMutableArray *friendsArray;

@end

@implementation JCFriendViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        [self setTitle: @"朋友"];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.functionArray = @[];
    self.functionArray = @[@[@"通讯录",@"APC_newFriend_icon"]];
    
    [self setAutomaticallyAdjustsScrollViewInsets:YES];
    [self setExtendedLayoutIncludesOpaqueBars:YES];
    
    UIColor *color = [UIColor colorWithRed:230/255.00 green:230/255.00 blue:230/255.00 alpha:1.0];
    self.searchbar.backgroundImage = [UIColorDispose imageWithColor:color size:CGSizeMake(SuperWidth, 64)];
    self.searchbar.backgroundColor = [UIColor colorWithRed:230/255.00 green:230/255.00 blue:230/255.00 alpha:1.0];
    
    self.tableView.tableFooterView = [[UIView alloc] init];
    self.tableView.separatorColor = [UIColor colorWithWhite:0.90 alpha:1.0];
    self.tableView.backgroundColor = ThemeColorBackgroundGary;
    
    //获取好友列表
    [self getFriendsList];
}

- (void)getFriendsList
{
    //获取好友列表
    if(self.friendsArray) [self.friendsArray removeAllObjects];
    self.friendsArray = [NSMutableArray arrayWithObject:self.functionArray];
    
//    NSArray *fetchedResults = [[self fetchedResultsController] fetchedObjects];
//    if(fetchedResults && fetchedResults.count > 0) {
//        [self.friendsArray addObject:fetchedResults];
//    }
    
//    [self.tableView setTableViewNotDataDrawText:@"暂无朋友" isShow:YES];
    [self.tableView reloadData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark NSFetchedResultsController
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

//- (NSFetchedResultsController *)fetchedResultsController
//{
//    if (fetchedResultsController == nil)
//    {
//        NSManagedObjectContext *moc = [[XMPPConnectService sharedService] managedObjectContext_roster];
//        
//        NSEntityDescription *entity = [NSEntityDescription entityForName:@"XMPPUserCoreDataStorageObject"
//                                                  inManagedObjectContext:moc];
//        
//        NSSortDescriptor *sd1 = [[NSSortDescriptor alloc] initWithKey:@"sectionNum" ascending:YES];
//        NSSortDescriptor *sd2 = [[NSSortDescriptor alloc] initWithKey:@"displayName" ascending:YES];
//        
//        NSArray *sortDescriptors = [NSArray arrayWithObjects:sd1, sd2, nil];
//        
//        NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
//        [fetchRequest setEntity:entity];
//        [fetchRequest setSortDescriptors:sortDescriptors];
//        [fetchRequest setFetchBatchSize:10];
//        
//        fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest
//                                                                       managedObjectContext:moc
//                                                                         sectionNameKeyPath:@"sectionNum"
//                                                                                  cacheName:nil];
//        [fetchedResultsController setDelegate:self];
//        
//        NSError *error = nil;
//        if (![fetchedResultsController performFetch:&error])
//        {
//            DDLogError(@"Error performing fetch: %@", error);
//        }
//    }
//    
//    return fetchedResultsController;
//}

- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller
{
    //获取好友列表
    [self getFriendsList];
}

#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.friendsArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSArray *array = self.friendsArray[section];
    return array.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 52;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellId = @"JCFriendViewCell";
    JCFriendViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    if (!cell) cell = [[JCFriendViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
    
    if (indexPath.section == 0) {
        NSArray *functionArray = self.friendsArray[indexPath.section];
        cell.titleLabel.text = functionArray[indexPath.row][0];
        cell.iconImageView.image = [UIImage imageNamed:functionArray[indexPath.row][1]];
    } else {
//        NSArray *infoArray = self.friendsArray[indexPath.section];
//        XMPPUserCoreDataStorageObject *object = infoArray[indexPath.row];
//        cell.titleLabel.text = object.nickname ? object.nickname : [object.jid user];
//        
//        if(object.photo){
//            cell.iconImageView.image = object.photo;
//        } else {
//            NSData *photoData = [[[XMPPConnectService sharedService] xmppvCardAvatarModule] photoDataForJID:object.jid];
//            if (photoData != nil) cell.iconImageView.image = [UIImage imageWithData:photoData];
//        }
    }
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0) return 0;
    else return 10;
}

//- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
//{
//    NSMutableArray *toBeReturned = [[NSMutableArray alloc]init];
//    
//    for(char c = 'A';c<='Z';c++)
//    [toBeReturned addObject:[NSString stringWithFormat:@"%c",c]];
//    
//    return toBeReturned;
//}

- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
{
//    NSInteger count = 0;
//    for(NSString *character in arrayOfCharacters) {
//        if([character isEqualToString:title])return count;
//        count ++;
//    }
    
    return 0;
}

//- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
//{
//    if([arrayOfCharacters count]==0) return @"";
//    return [arrayOfCharacters objectAtIndex:section];
//}

#pragma mark - UITableViewDataSource


-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [tableView setSeparatorInset:UIEdgeInsetsZero];
    }
    
    if ([tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [tableView setLayoutMargins:UIEdgeInsetsZero];
    }
    
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
//    if (indexPath.section > 0) {
//        NSArray *infoArray = self.friendsArray[indexPath.section];
//        XMPPUserCoreDataStorageObject *object = infoArray[indexPath.row];
//        
//        JBChatFriendViewController *viewController = [[JBChatFriendViewController alloc] initWithJID:object.jid];
//        [self.navigationController pushViewController:viewController animated:YES];
//    }
    
    if(indexPath.row == 0){
        OAAddressBookCatalogViewController *viewController = [[OAAddressBookCatalogViewController alloc] init];
        [self.navigationController pushViewController:viewController animated:YES];
    }
    
}


#pragma mark - UISearchDisplayDelegate methods

-(BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString {
    
//    [self filterContentForSearchText:searchString scope:[[controller.searchBar scopeButtonTitles]                                       objectAtIndex:[controller.searchBar selectedScopeButtonIndex]]];
    
    return YES;
    
}

- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchScope:(NSInteger)searchOption {
    
//    [self filterContentForSearchText:[controller.searchBar text] scope:
//     [[controller.searchBar scopeButtonTitles] objectAtIndex:searchOption]];
    
    return YES;
    
}

@end
